/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.companhia.web;

/**
 *
 * @author Andre
 */
import br.com.companhia.util.HibernateUtil;
import javax.servlet.*;
import org.hibernate.SessionFactory;

public class ConexaoHibernateFilter implements Filter {

    private SessionFactory sf;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        sf = HibernateUtil.getSessionFactory();
    }

    @Override
    public void doFilter(ServletRequest servlerRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException {

        try {
            sf.getCurrentSession().beginTransaction();
            chain.doFilter(servlerRequest, servletResponse);
            sf.getCurrentSession().getTransaction().commit();
            sf.getCurrentSession().close();
        } catch (Throwable ex) {
            try {
                if (sf.getCurrentSession().getTransaction().isActive()) {
                    sf.getCurrentSession().getTransaction().rollback();
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
            throw new ServletException(ex);
        }

    }

    @Override
    public void destroy() {

    }

}
